﻿using System;
using System.Collections.Generic;
using System.Drawing.Drawing2D;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
using System.IO;
using Windows.Graphics;

namespace FileManager.Util
{
    public static class ImageUtil
    {
        public static Bitmap ResizeImageToWidth(this Bitmap originalImage, int targetWidth)
        {
            if (originalImage == null)
                throw new ArgumentNullException(nameof(originalImage));
            int originalWidth = originalImage.Width;
            int originalHeight = originalImage.Height;

            // 判断长边和短边
            bool needsRotation = originalHeight < originalWidth;

            // 如果需要旋转，则旋转图像
            if (needsRotation)
            {
                originalImage = RotateImage90(originalImage);
            }

            // 计算新的高度，以保持长宽比
            float heightRatio = (float)targetWidth / originalImage.Width;
            int targetHeight = (int)(originalImage.Height * heightRatio);

            // 创建目标大小的新Bitmap
            Bitmap resizedImage = new Bitmap(targetWidth, targetHeight);

            // 使用Graphics类绘制缩放后的图像
            using (Graphics graphics = Graphics.FromImage(resizedImage))
            {
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.DrawImage(originalImage, 0, 0, targetWidth, targetHeight);
            }

            return resizedImage;
        }

        public static void  Update(this BitmapImage disPlayPic,string savePath)
        {
            // 创建编码器
            JpegBitmapEncoder encoder = new JpegBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(disPlayPic));
            // 将图像保存为文件
            using (FileStream fs = new FileStream(savePath, FileMode.OpenOrCreate, FileAccess.Write))
            {
                encoder.Save(fs);
            }
        }
        private static Bitmap RotateImage90(Bitmap originalImage)
        {
            if (originalImage == null)
                throw new ArgumentNullException(nameof(originalImage));

            // 创建一个与原图相同大小的新Bitmap，用于绘制旋转后的图像
            Bitmap rotatedImage = new Bitmap(originalImage.Height, originalImage.Width);
            using (var g = Graphics.FromImage(rotatedImage))
            {
                // 设置旋转中心点为图片中心
                g.TranslateTransform(rotatedImage.Width / 2, rotatedImage.Height / 2);
                // 旋转90度
                g.RotateTransform(90);

                // 绘制旋转后的图片
                g.DrawImage(originalImage, new RectangleF(-originalImage.Width / 2, -originalImage.Height / 2, originalImage.Width, originalImage.Height));

                //graphics.DrawImage(originalImage, new Point(0, 0));
            }
            // 清理资源
            originalImage.Dispose();
            return rotatedImage;
        }
    }

}
